<?php
require_once('php/util/util.php');
require_once('php/db/connect.php');

$email = $_GET["email"];
$password = $_GET["password"];
$remember = $_GET['remember'];
echo $email . ',' . $password . ',' . $remember;

if (isset($email) && isset($password)) {

    if (validateUser($email,$password)) {       
        if (isset($remember)) {
            /* Set cookie to last 1 year */
            setcookie('email', $email, time() + 60 * 60 * 24 * 365);
            setcookie('password', $password, time() + 60 * 60 * 24 * 365);
            $_SESSION['email']=$email;
        } else {
            /* Cookie expires when browser closes */
            setcookie('email', $email, false);
            setcookie('password', $password, false);
            $_SESSION['email']=$email;
        }        
        echo '<br/>' . $email . " is logged into foggy.";
        echo '<br/>' . "Log out using <a href=" . getLogoutAjaxUrl() . "> this link </a><br/>";
    } else {
        drawLoginForm();
        echo '<br/>Username/Password Invalid';
    }
} else {
    drawLoginForm();
    echo '<br/>You must supply a username and password.';
}

function validateUser($username, $password) {
    $con = getNewDatabaseConnection();

    $sql = "select email from foggy.users where email = $1 and password = $2";
    $result = pg_query_params($con, $sql, array($username, $password)) or die("Error in SQL query: " . pg_last_error());

    // iterate over result set
    // print each row
    $count = 0;
    while ($row = pg_fetch_array($result)) {
        $count ++;
    }

    // free memory
    pg_free_result($result);

    // close connection
    pg_close($con);
    echo "<br/>Found " . $count . " users.";
    return $count > 0;
}

function drawLoginForm() {
    echo '<form class="login">';
    echo '<strong>Member Login</strong>';
    echo '<table>';
    echo '<tr>';
    echo '<td>';
    echo '<p>Email</p>';
    echo '</td>';
    echo '<td>';
    echo '<input name="email" type="text" id="email" />';
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td>';
    echo '<p>Password</p>';
    echo '</td>';
    echo '<td>';
    echo '<input name="password" type="password" id="password" />';
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td>';
    echo '<p>Remember Me</p>';
    echo '</td>';
    echo '<td>';
    echo '<input name="remember" type="checkbox" id="remember" />';
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td>';
    echo '<button id="loginButton" type="button" onclick="login(document.getElementById(\'email\').value, document.getElementById(\'password\').value, document.getElementById(\'remember\').value);"/>Login</button>';
    echo '</td>';
    echo '<td>';
    echo '</td>';
    echo '</tr>';
    echo '</table>';
    echo '</form>';
}

?>
